import mysql from 'mysql';

export interface ImysqlConfig {
  host: string;
  port: number;
  database: string;
  user: string;
  password: string;
}

export class MySQLUtils {
  private connection: any;

  static instance: {
    connect: (mysqlConfig: ImysqlConfig) => void;
    query: (sql: string, params?: any) => Promise<unknown> | undefined;
    end: () => void;
  };

  static getInstance() {
    // 判断是否已经new过1个实例
    if (!MySQLUtils.instance) {
      // 若这个唯一的实例不存在，那么先创建它
      MySQLUtils.instance = new MySQLUtils();
    }
    // 如果这个唯一的实例已经存在，则直接返回
    return MySQLUtils.instance;
  }

  constructor() {
    this.connection = null;
  }
  connect(mysqlConfig: ImysqlConfig) {
    this.connection = mysql.createConnection({
      ...mysqlConfig,
      supportBigNumbers: true,
      bigNumberStrings: true,
    });

    this.connection.connect();
  }

  query(sql: string, params?: any) {
    if (!this.connection) {
      return;
    }
    return new Promise((resolve) => {
      this.connection.query(sql, params, function (err: Error, result: any) {
        if (err) {
          console.error('mysql query error---', err);
          resolve({});
        } else {
          resolve(result);
        }
      });
    });
  }

  end() {
    this.connection && this.connection.end();
  }
}
